window.onload = function() {
    var request,
        hrq = new XMLHttpRequest();

    request = 'http://desanti.org/endpoint.php?output=json&query=' + 
              encodeURIComponent ("\
              PREFIX terms: <http://desanti.org/schemas/collections#>\
              SELECT ?image WHERE {\
               ?page a terms:Page .\
               { ?page terms:image ?image . }\
               UNION\
               { ?page terms:thumbnail ?image . }\
              }");

    hrq.open("GET", request);

    hrq.onload = function () {
        var data = eval( "(" + hrq.responseText + ")" ),
            results = data.results.bindings,
            nextImage,
            domImage,
            imageLoaded;

        imageLoaded = function ( ) {
            var request,
                hrq2 = new XMLHttpRequest(); 

            request = 'query=' + 
                      encodeURIComponent ("\
                      PREFIX terms: <http://desanti.org/schemas/collections#>\
                      INSERT INTO <http://desanti.org/> {\
                        <"+domImage.src+"> terms:hasWidth \""+domImage.width+"\" . \
                        <"+domImage.src+"> terms:hasHeight \""+domImage.height+"\" . \
                      }");
            hrq2.open("POST", "http://desanti.org/endpoint.php");
            hrq2.send(request);
            hrq2.onload = function ( ) {
                document.getElementById("results").innerHTML = domImage.src;
                nextImage();
            }
        }

        nextImage = function ( ) {
            domImage = document.createElement("img");
            domImage.setAttribute("src", results.pop().image.value);
            if(domImage.complete) {
                imageLoaded();
            } else {
                domImage.onload = imageLoaded;
            }
        }

        nextImage();

    }

    hrq.send(null);
}
